<template>
	<view class="my_area">
		<uni-data-picker ref="picker" :placeholder="watVal" popup-title="请选择所在地区" :localdata="ArrList" v-model="areaVal" :map="map" @change="onchange">
		</uni-data-picker>
	</view>
</template>

<script>
	import api from '@/utils/api';
	import { http,storage } from '@/utils/utils.js';
	export default {
		name: "my-area",
		data() {
			return {
				map: {
					text: 'name',
					value: 'id'
				},
				ArrList:[],
				areaVal: null,
			};
		},
		props:{
			watVal: {
				type: String,
				default: '请选择所在地区'
			}
		},
		mounted() {
			/**
			 * 获取地区
			 */
			this.getRegionInfo().then((res) => {
				//地区格式化
				this.formatArea(res)
			});
		},
		
		watch: {
		  // 监听的属性名，参数为新旧值
		  'watVal'(newVal, oldVal) {
		    // 对属性变化作出响应
			console.log('newVal, oldVal',newVal)
			if(newVal) this.areaVal = newVal
		  }
		},
		methods: {
			onchange(e) {
				let { value } = e.detail;
				let location = null;
				let locationId = null
				if(value.length>0){
					location = value[0].text + value[1].text + value[2].text;
					locationId = [value[0].value , value[1].value , value[2].value];
				}
				console.log('onchange----value:', location,locationId);
				this.$emit('change',{location,locationId})
			},
			// 递归数组
			formatArea(arr) {
				let ArrList = arr;
				if(Array.isArray(ArrList) && ArrList.length>0){
					ArrList.forEach(atem=>{
						if(Array.isArray(atem.list)&&atem.list.length>0){
							atem['children'] = atem.list;
							delete atem.list
							atem.children.forEach(btem=>{
								if(Array.isArray(btem.list)&&btem.list.length>0){
									btem['children'] = btem.list;
									delete btem.list
								}else{
									btem['children'] = btem.list;
									delete btem.list
								}
							})
						}
					})
				}
				this.ArrList = ArrList;
				console.log('ArrList==============',ArrList)
			},
			/**
			 * 获取地区
			 */
			getRegionInfo() {
				return new Promise((resolve) => {
					storage
						.get('regionInfo')
						.then((res) => {
							console.log('myarea1----------------->', res)
							this.regionInfo = res;
							resolve(res);
						})
						.catch((res) => {
							http.get(
								api.default, {
									data: {
										action: 'district'
									}
								},
								false
							).then((res) => {
								const {
									data
								} = res.data;
								console.log('myarea-data----------------->', data)
								this.regionInfo = data;
								storage.set('regionInfo', data);
								resolve(data);
							});
			  	});
				});
			},
		}
	}
</script>

<style lang="scss">

</style>
